package com.example.a1.fannong.core.manager.user;

import android.content.SharedPreferences;
import android.support.annotation.NonNull;

import com.example.a1.fannong.core.app.BaseManager;
import com.example.a1.fannong.core.app.MyApplication;
import com.example.a1.fannong.core.http.OnResultListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.personal.library.json.JsonHelper;

/**
 * 用户管理类
 * Created by nishuhang on 16/12/30.
 */
public class UserManager extends BaseManager {
    public final static String ALL_VIDEO_ROLE = "智慧消费：教育局";
    public final static String SINGLE_VIDEO_ROLE = "智慧消费：学校";
    public final static String NORMAL_VIDEO_ROLE = "智慧消费：消费者";
    private User user;
    private List<OnUserStateChangeListener> onUserStateChangeListeners = new ArrayList<>();
    private List<OnUserInfoChangeListener> onUserInfoChangeListenerList = new ArrayList<>();

    private VerifyCodeController verifyCodeController;
    private boolean isOnLogin = false;

    @Override
    public void onManagerCreate(MyApplication application) {
        loadUser();

        // 短信发送计时器 间隔时间  60秒
        verifyCodeController = new VerifyCodeController(60 * 1000);
    }

    /**
     * 短信发送验证器
     */
    public VerifyCodeController getVerifyCodeController() {
        return verifyCodeController;
    }

    private void loadUser() {
        SharedPreferences sharedPreferences = getApplication().getSharedPreferences("user_info", 0);
        String userInfo = sharedPreferences.getString("user", "{}");

        try {
            user = JsonHelper.toObject(new JSONObject(userInfo), User.class);
        } catch (JSONException e) {
            e.printStackTrace();
            user = new User();
        }
    }

    private void saveUser(User user) {
        SharedPreferences sharedPreferences = getApplication().getSharedPreferences("user_info", 0);
        sharedPreferences.edit().putString("user", JsonHelper.toJSONObject(user).toString()).apply();
        this.user = user;
    }

    /**
     * 获取当前登录用户
     */
    @NonNull
    public User getUser() {
        return user.clone();
    }

    public String getUid() {
        return getUser().getUid();
    }

    /**
     * 用户是否已经登录
     *
     * @return true: 已登录, false:未登录
     */
    public boolean isLogin() {
        return !getUid().equals("");
    }

    /**
     * 添加用户登录登出监听
     */
    public void addOnUserStateChangeListener(OnUserStateChangeListener onUserStateChangeListener) {
        onUserStateChangeListeners.add(onUserStateChangeListener);
    }

    public void removeOnUserStateChangeListener(OnUserStateChangeListener onUserStateChangeListener) {
        onUserStateChangeListeners.remove(onUserStateChangeListener);
    }

    public User getUserWithoutClone() {
        return user;
    }

    private void notifyUserInfoChange() {
        List<OnUserInfoChangeListener> onUserInfoChangeListeners = new ArrayList<>(onUserInfoChangeListenerList);
        for (OnUserInfoChangeListener onUserInfoChangeListener : onUserInfoChangeListeners) {
            onUserInfoChangeListener.onUserInfoChange(getUser());
        }
    }

    /**
     * 添加用户信息变化监听
     */
    public void addOnUserInfoChangeListener(OnUserInfoChangeListener onUserInfoChangeListener) {
        onUserInfoChangeListenerList.add(onUserInfoChangeListener);
    }

    public void removeOnUserInfoChangeListener(OnUserInfoChangeListener onUserInfoChangeListener) {
        onUserInfoChangeListenerList.remove(onUserInfoChangeListener);
    }

//    /**
//     * 注册
//     *
//     * @param phone            手机号
//     * @param code             验证码
//     * @param pwd              密码  原始密码
//     * @param onResultListener 结果监听器
//     */
//    public void register(String phone, String code, String pwd, long uid, final OnResultListener<Integer> onResultListener) {
//        RegisterRequester requester = new RegisterRequester(onResultListener);
//        requester.phone = phone;
//        requester.passWord = pwd;
//        requester.verifyCode = code;
//        requester.uid = uid;
//        requester.doPost(500);
//    }

//    /**
//     * 登录接口
//     *
//     * @param phoneNum         登录手机号
//     * @param pwd              密码
//     * @param onResultListener 结果监听
//     */
//    public void login(final String phoneNum, String pwd, final OnResultListener<User> onResultListener) {
//        if (isLogin()) {
//            throw new RuntimeException("已经登录，请勿重复登录");
//        }
//        if (isOnLogin) {
//            onResultListener.onResult(OnResultListener.RESULT_FAILED, "正在登录中，请勿重复登录", null);
//            return;
//        }
//        isOnLogin = true;
//        LoginRequester loginRequester = new LoginRequester(new OnResultListener<User>() {
//            @Override
//            public void onResult(int result, final String msg, final User tempUser) {
//                if (result == RESULT_SUCCESS) {
//                    isOnLogin = false;
//                    saveUser(tempUser);
//                    // 通知 用户登录了
//                    List<OnUserStateChangeListener> listeners = new ArrayList<>(onUserStateChangeListeners);
//                    for (OnUserStateChangeListener listener : listeners) {
//                        listener.onUserLogin();
//                    }
//                    onResultListener.onResult(result, msg, getUser());
//                } else {
//                    isOnLogin = false;
//                    onResultListener.onResult(result, msg, getUser());
//                }
//
//            }
//        });
//        loginRequester.passWord = pwd;
//        loginRequester.phone = phoneNum;
//        loginRequester.doPost(500);
//    }

    public void logout(final OnResultListener<User> onResultListener) {
        if (!isLogin()) {
            throw new RuntimeException("已经退出登录，请勿重复操作");
        }
        if (isOnLogin) {
            MyApplication.HANDLER.postDelayed(new Runnable() {
                @Override
                public void run() {
                    logout(onResultListener);
                }
            }, 1000);
            return;
        }

        User user = new User();
        user.setUid("");
        saveUser(user);
        // 通知 用户登录了
        List<OnUserStateChangeListener> listeners = new ArrayList<>(onUserStateChangeListeners);
        for (OnUserStateChangeListener listener : listeners) {
            listener.onUserLogout();
        }
        onResultListener.onResult(OnResultListener.RESULT_SUCCESS, "退出登录成功", getUser());
    }

//    /**
//     * 上传头像
//     *
//     * @param file
//     * @param onResultListener
//     */
//    public void uploadAvatar(final File file, final OnResultListener<String> onResultListener) {
//        AsyncHttpClient client = new AsyncHttpClient();
//
//        File[] fileSize = new File[1];
//            fileSize[0] = file;
//        RequestParams requestParams = new RequestParams();
//        try {
//            requestParams.put("file", file);
//            requestParams.put("userId", getUid());
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
//        client.post(MyApplication.getInstance().getApplicationContext(), "http://test.isum.cn/wisdom/app/user/modHeadImg", requestParams, new AsyncHttpResponseHandler() {
//            @Override
//            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//                try {
//                    String string = new String(responseBody, "UTF-8");
//                    JSONObject json = new JSONObject(string);
//                    int state = json.optInt("state");
//                    if(state == OnResultListener.RESULT_SUCCESS){
//                        JSONObject dataJson = json.optJSONObject("data");
//                        String imageFileName = dataJson.optString("headImg");
//                        modifyAvatarFileName(imageFileName);
//                        onResultListener.onResult(OnResultListener.RESULT_SUCCESS, "", file.getAbsolutePath());
//                    }else{
//                        onResultListener.onResult(OnResultListener.RESULT_FAILED, "", file.getAbsolutePath());
//                    }
//
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//
//            }
//
//            @Override
//            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
//                onResultListener.onResult(OnResultListener.RESULT_FAILED, "", "");
//            }
//        });
//    }
//
//    private void modifyAvatarFileName(String fileName) {
//        user.setAvatarUr(fileName);
//        saveUser(user);
//        notifyUserInfoChange();
//
//    }
//
//    public void modifyNickName(final String nickName, final OnResultListener onResultListener) {
//
//        ModifyNickNameRequester modifyNickNameRequester = new ModifyNickNameRequester(new OnResultListener<Void>() {
//            @Override
//            public void onResult(int result, String msg, Void aVoid) {
//                onResultListener.onResult(result, "", "");
//                if (result == RESULT_SUCCESS) {
//                    user.setNickName(nickName);
//                    saveUser(user);
//                    notifyUserInfoChange();
//                }
//            }
//        });
//        modifyNickNameRequester.userId = getUid();
//        modifyNickNameRequester.name = nickName;
//        modifyNickNameRequester.doPost();
//
//    }

    public List<String> getRoleList(){
        String[] role = user.getRoleName().split(",");
        List<String> roleList = Arrays.asList(role);
        return roleList;
    }
}
